<template>
  <div class="pageBox">
    <div class="tabBox flexBox aiCenter flexAround mb15">
      <div v-for="item in tabData.list" :key="item.value"
        :class="['fs28', 'c-333', 'tabItem', { 'activeTab': item.value === tabData.curTab }]"
        @click="changeTab(item.value)">
        {{ item.label }}
      </div>
    </div>
    
    <div v-if="isShowSkeleton" class="mt20">
      <van-skeleton title :row="5" />
    </div>
    <div v-else>
      <div class="wallet-wrapper" ref="walletScrollWrap">
        <van-empty description="暂无数据" v-if="!total" />

        <div class="wallet">
          <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
            <van-list v-if="total > 0" v-model:loading="loading" :finished="finished" finished-text="没有更多了"
              v-model:error="error" error-text="请求失败，点击重新加载" @load="onLoad" :offset="50">
              <div v-for="item in list" :key="item.id" class="walletItem">
                <div class="flexBox aiCenter flexBetween">
                  <div class="flexBox aiCenter">
                    <img :src="moneyIcon" alt="" class="avatar mr30">
                    <div>
                      <div class="fs28 f600 c-333">{{ walletType[item.type] || '-' }}</div>
                      <div class="fs24 c-999">{{ changeTime(item.create_time, 'YYYY-MM-DD HH:mm:ss') }}</div>
                    </div>
                  </div>
                  <div class="fs28 f600 c-333">{{ item.fee }}</div>
                </div>
              </div>
            </van-list>
          </van-pull-refresh>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, onUnmounted, reactive, ref } from 'vue'
import { walletLogList } from '@/api/user'
import { changeTime } from '@/utils'
import { useRoute } from 'vue-router'
import { CommonPage, WalletLogListType } from '@/types/userTypes'
import moneyIcon from '@/assets/images/money.png'
import { walletType } from '@/types/mock'

const list = ref<WalletLogListType[]>([])
const total = ref(0)
const loading = ref(false)
const finished = ref(false)
const refreshing = ref(true)
const error = ref(false)
const isShowSkeleton = ref(true)
const walletScrollWrap = ref<HTMLDivElement | null>(null)

const tabData = reactive({
  curTab: -1,
  list: [
    { label: '全部', value: -1 },
    { label: '收入', value: 1 },
    { label: '支出', value: 2 }
  ]
})
const pageData = reactive({
  page: 1,
  pageSize: 10
})

const route = useRoute()

const getList = async () => {
  if (list.value.length >= total.value && list.value.length > 0) {
    loading.value = false
    finished.value = true
    return
  }
  try {
    const params = { ...pageData, type: tabData.curTab } as { user_id: number, type: number } & CommonPage
    if (route.query.userId) {
      params.user_id = Number(route.query.userId)
    }
    const { data } = await walletLogList(params)
    if (data.code === 0) {
      isShowSkeleton.value = false
      list.value = [...list.value, ...data.data.entries]
      total.value = data.data.total
      finished.value = list.value.length === total.value
    }
  } catch (err) {
    error.value = true
  }
  loading.value = false
}

const onLoad = () => {
  setTimeout(() => {
    pageData.page++
    getList()
  }, 500)
}

const onRefresh = () => {
  list.value = []
  pageData.page = 1
  setTimeout(() => {
    getList()
    refreshing.value = false
  }, 500)
}

// 滚动时显示滚动条
const handleScroll = () => {
  if (walletScrollWrap.value) {
    // 现代浏览器：修改滚动条颜色
    walletScrollWrap.value.style.scrollbarColor = 'rgba(191, 191, 191, 0.8) rgba(191, 191, 191, 0.2)'

    // 清除自动隐藏的定时器
    if (window.scrollBarTimer) {
      clearTimeout(window.scrollBarTimer)
    }

    // 滚动停止后，延迟隐藏滚动条
    window.scrollBarTimer = setTimeout(() => {
      walletScrollWrap.value!.style.scrollbarColor = 'rgba(0, 0, 0, 0) rgba(0, 0, 0, 0.1)'
    }, 500)
  }
}

const changeTab = (value: number) => {
  if (tabData.curTab === value) return
  tabData.curTab = value
  list.value = []
  pageData.page = 1
  finished.value = false
  error.value = false
  isShowSkeleton.value = true
  loading.value = true
  getList()
}

onMounted(() => {
  getList()
  if (walletScrollWrap.value) {
    walletScrollWrap.value.addEventListener('scroll', handleScroll)
  }
})

onUnmounted(() => {
  if (walletScrollWrap.value) {
    walletScrollWrap.value.removeEventListener('scroll', handleScroll)
    clearTimeout(window.scrollBarTimer)
  }
})
</script>

<style lang="scss" scoped>
.pageBox {
  background: #ffffff;
  padding-top: 10px;
  height: 100%;
  display: flex;
  flex-direction: column;

  .wallet-wrapper {
    flex: 1;
    overflow-y: auto;
    scrollbar-width: thin;
    padding: 0 20px;
    scrollbar-color: rgba(0, 0, 0, 0) rgba(0, 0, 0, 0.1);
    transition: scrollbar-color 0.3s ease;

    // WebKit 内核浏览器
    &::-webkit-scrollbar {
      width: 4px;
    }

    &::-webkit-scrollbar-track {
      background: rgba(0, 0, 0, 0.1);
      // 轨道浅灰色
    }

    &::-webkit-scrollbar-thumb {
      background-color: rgba(0, 0, 0, 0);
      // 初始透明
      border-radius: 2px;
      transition: background-color 0.3s ease;
    }

    &:hover::-webkit-scrollbar-thumb,
    &:scrollbarthumbvertical::-webkit-scrollbar-thumb {
      background-color: rgba(0, 0, 0, 0.4);
    }

    .wallet {
      width: 100%;

      .walletItem {
        margin-bottom: 5px;
        padding: 15px 0;
        border-bottom: 1px solid #F2F2F2;

        .avatar {
          width: 65px;
          height: 65px;
          border-radius: 50%;
        }
      }
    }
  }
}

.activeTab {
  position: relative;

  &::after {
    content: '';
    position: absolute;
    bottom: -8px;
    left: 0;
    width: 100%;
    height: 4px;
    background: #40a9ff;
    border-radius: 2px;
  }
}
</style>